import React, { Component } from 'react';
import ThePagination from "@/components/ThePagination";
import { Form, Input, Select, Space, Button, DatePicker,Tooltip, Tag, Modal } from "antd";
import { SearchOutlined,QuestionCircleOutlined } from "@ant-design/icons";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import TheQueryForm from '../../../components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import store from "@/store/store"
import _ from 'lodash';
import { getDateTime3 } from '@/utils/getDate'
import { exportSheetTable } from '@/utils/exportTable.js';
import { apiStockInLibraryPage, apiStockInLibraryDel,apiTSysDictionariesList,apiPostVoucherCode, apiPrintInLibraryOrderList } from '@/request/storageManager/putIn.js'
const dataTypes = [{ label: '采购入库单转入库单', value: '1', }, { label: '商城退货退款入库单', value: '2', }, { label: '门店退货退款入库单', value: '3', }, { label: '门店收银台退货', value: '4', }, { label: '手动创建入库单', value: '5', }, { label: '门店收银台取消订单', value: '6', },{ label: '调拨入库单', value: '7', },]
export default class OutPut extends Component {
    constructor() {
        super()
        this.formRef_search = React.createRef()
        this.queryFormRef = React.createRef()
        this.voucherFormRef = React.createRef()
        this.state = {
            columns: [
                {
                    title: "序号",
                    dataIndex: "index",
                    key: "index",
                    render:(text,record,index) =>{
                        return((this.state.pageData.pageNo - 1)*(this.state.pageData.pageSize) + (index + 1));
                    }
                },
                {
                    title: "入库单号",
                    dataIndex: "code",
                    key: "code",
                },
                {
                    title: "对应单号",
                    dataIndex: "otherCode",
                    key: "otherCode",
                    filterDropdown: true, // 自定义的列筛选功能，我们占位为信息提示Icon的位置
                    filterIcon: () => {
                       return (
                        <Tooltip zIndex={999} placement="top" title={()=>{
                           return <div>
                            采购单生成入库单：采购单号<br />
                            商城退货生成入库单：商城退货单号<br />
                            门店退货生成入库单：门店订单号<br />
                            收银台退货生成入库单：门店订单号<br />
                            收银台取消订单：门店订单号<br />
                            调拨入库单：出库单号
                           </div>
                        }
                        }  >
                            <QuestionCircleOutlined />
                        </Tooltip>
                       );
                      },
                },
                {
                    title: "入库日期",
                    dataIndex: "finishTime",
                    key: "finishTime",
                },
                {
                    title: "入库类型",
                    dataIndex: "dataType",
                    key: "dataType",
                    render: (text, render) => {
                        let obj = dataTypes.find(item => item.value == text);
                        return obj === undefined ? '' : obj.label

                    }
                },
                {
                    title: "入库仓库",
                    dataIndex: "libraryName",
                    key: "libraryName",
                },
                {
                    title: "供应商",
                    dataIndex: "supplierName",
                    key: "supplierName",
                },
                {
                    title: "状态",
                    dataIndex: "status",
                    key: "status",
                    render: (text) => {
                        if (text == 0) {
                            return <div style={{color:"red"}} >未完成</div>
                        } else {
                            return '已完成'
                        }
                    }
                },
                {
                    title: "登记人",
                    dataIndex: "memberName",
                    key: "memberName",

                },
                {
                    title: "凭证编码",
                    dataIndex: "voucherCode",
                    key: "voucherCode"
                },
                {
                    title: "登记日期",
                    dataIndex: "createTime",
                    key: "createTime",
                    defaultChange:true
                }, {
                    title: "操作",
                    dataIndex: "serviceShowFile",
                    key: "serviceShowFile",
                    fixed:'right',
                    render: (text, render) => {
                        return <div>
                            <TheButton haspermi={['storage:putIn:voucher']} onClick={() => this.voucher(render)}>编辑凭证</TheButton>
                            <TheButton haspermi={['storage:putIn:view']} onClick={() => this.props.history.push('/outPutManager/putIn/add/' + render.id)}>查看详情</TheButton>
                            <TheButton haspermi={['storage:putIn:del']} onClick={() => this.del(render)}>删除</TheButton>
                        </div>
                    }
                },
            ],
            newColumns: [],
            form_show: true,
            searchOption: [
                { field: 'code', label: '入库单号', placeholder: '请输入入库单号', required: false, rules: [], type: 'Input', defaultValue: '' },
                // { field: 'libraryName', label: '入库仓库', placeholder: '请选择入库仓库', required: false, rules: [], type: 'Input', options: [], defaultValue: '' },
                { field: 'otherCode', label: '对应单号', placeholder: '请输入对应单号', required: false, rules: [], type: 'Input', defaultValue: '' },
                { field: 'supplierName', label: '供应商', placeholder: '请选择供应商', required: false, rules: [], type: 'Input', options: [], defaultValue: '' },
                { field: 'dataType', label: '入库类型', placeholder: '请选择入库类型', required: false, rules: [], type: 'Select', options: [], defaultValue: '', txt: 'name', value: 'value', api: apiTSysDictionariesList,params: { pid: '1603276509641211906' } },
                { field: 'status', label: '状态', placeholder: '请选择状态', required: false, rules: [], type: 'Select', options: [{ label: '未完成', value: '0', }, { label: '已完成', value: '1' }], defaultValue: '' },
                { field: 'time', label: '入库日期', placeholder: '请选择', required: false, rules: [], type: 'RangePicker' },
                // { field: 'memberName', label: '登记人', placeholder: '请输入登记人', required: false, rules: [], type: 'Input', defaultValue: '' },
                // { field: 'times', label: '入库日期', placeholder: '', required: false, rules: [], type: 'RangePicker', defaultValue: '' },
            ],
            queryForm: {},
            dataSource: [],
            pageData: {
                pageNo: 1,
                pageSize: 10
            }, 
            total: 0,
            code: '',
            sumCount:"",
            sumPrice:"",
            visible:false,
            selectedKeys: { 1: [] },
            vouchercode:''
        }
    }
    componentDidMount() {
        this.onColumnsFilter(this.state.columns)
        let searchParams = store.getState().searchValue
        let { pageNo, pageSize, queryForm, pathName } = searchParams
        if (searchParams && pageNo && pathName == 'putIn') {
            let { pageNo, pageSize, code } = searchParams
            this.setState({
                code,
                pageData: {
                    pageNo: pageNo, pageSize: pageSize
                }
            }, () => {
                this.queryFormRef.onSetDefault({ ...queryForm })
                // this.formRef_search.current.setFieldsValue({
                //     code
                // })
                this.getData()
            })
        } else {
            this.getData()
        }
    }
    getData(values) {
        let { pageNo, pageSize } = this.state.pageData
        if (values && !_.isEmpty(values.time)) {
            values.finishTimeStart = getDateTime3(values.time[0]) + ' 00:00:00'
            values.finishTimeEnd = getDateTime3(values.time[1]) + ' 23:59:59'
        }
        this.setState({
            queryForm: values === undefined ? this.state.queryForm : { ...values }
        }, async () => {
            const params = {
                pageNo, pageSize, queryForm: this.state.queryForm
            }
            store.dispatch({
                type: 'SaveSearchValues',
                data: {
                    pathName: 'putIn',
                    ...params
                }
            })
            await apiStockInLibraryPage({
                pageNo, pageSize, ...this.state.queryForm,
                firstTypeId:"1603276509641211906"
            }).then(res=>{
                if (res.code === 0 && res.data.sum !== null) {
                    this.setState({
                        dataSource: res.data.resultPage,
                        total: res.totalCount,
                        sumCount:res.data.sum.sumCount,
                        sumPrice:res.data.sum.sumPrice/100,
                    })
                }else {
                    this.setState({
                        dataSource: res.data.resultPage,
                        total: res.totalCount,
                        sumCount:"0",
                        sumPrice:"0",
                    })
                }
            })

        })

    }
    del(row) {
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: "确定是否删除？",
            onOk: async () => {
                let res = await apiStockInLibraryDel({ id: row.id })
                if (res.code === 0) {
                    this.pageChange(1, 10)
                    React.$message({
                        type: 'success',
                        content: res.codeMessage
                    })
                } else {
                    React.$message({
                        type: 'warning',
                        content: res.codeMessage
                    })
                }
            }
        });
    }
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo, pageSize
            }
        }, () => {
            this.getData()
        })
    };
    onReset() {
        this.setState({
            queryForm: {}
        }, () => {
            this.pageChange(1, 10)
        })
    }
    onTableRefresh() {
        this.getData()
    }
    onColumnsFilter(value) {
        this.setState({
            newColumns: value
        })
    }
    onFormSearch(values){
        this.setState({
            pageData: {pageNo:1,pageSize:10}
        },()=>{
            this.getData(values)
        })
    }
    voucher = (value) => {
        this.setState({
            visible:true,
            inLibraryId: value.id,
            vouchercode: value.voucherCode??""
        },()=>{
            this.voucherFormRef.setFieldsValue({voucherCode:this.state.vouchercode})
        })
    }
    handleCancel = () => {
        this.setState({
            visible: false,
            vouchercode:''
        })
    };
    editVoucher = async (values) => {
        const { inLibraryId } = this.state
        let res = await apiPostVoucherCode({ inLibraryId, ...values})
        if(res.code === 0){
            React.$message({
                type: 'info',
                content: res.codeMessage
            })
            this.handleCancel()
            this.getData()
        }
    }
    onChange = (selectedRowKeys, selectedRows) => {
        let pageNo = this.state.pageData.pageNo
        let selectedKeys = { ...this.state.selectedKeys }
        selectedKeys[pageNo] = selectedRowKeys
        this.setState({
            selectedKeys
        }, () => {  })
    }
    toExport = async () => {
        const { queryForm } = this.state
        let ids = ""
        if (queryForm && !_.isEmpty(queryForm.time)) {
            queryForm.finishTimeStart = getDateTime3(queryForm.time[0])
            queryForm.finishTimeEnd = getDateTime3(queryForm.time[1])
        }
        Object.values(this.state.selectedKeys).forEach(value => {
            ids += value.toString() + ","
        })
        if (ids === ",") {
            ids = ""
        }
        await apiPrintInLibraryOrderList({ ...queryForm ,ids, firstTypeId:"1603276509641211906" }).then(res => {
            if (res.code === 0 && res.data) {
                let th_arr = [
                    {
                        title: '采购入库单详情',
                        prop: '',
                        children: [
                            {
                                title: '序号',
                                prop: 'index',
                            },
                            {
                                title: '入库单号',
                                prop: 'code',
                            },
                            {
                                title: '对应单号',
                                prop: 'otherCode',
                            },
                            {
                                title: '入库总数量',
                                prop: 'num',
                                valueType: 'number'
                            },
                            {
                                title: '入库完成时间',
                                prop: 'finishTime',
                            },
                            {
                                title: '入库单备注',
                                prop: 'remark',
                            },
                            {
                                title: '入库类型名称',
                                prop: 'inLibraryTypeName',
                            },
                            {
                                title: '仓库名称',
                                prop: 'libraryName',
                            },
                            {
                                title: '供应商',
                                prop: 'supplierName',
                            },
                            {
                                title: '状态',
                                prop: 'status',
                            },
                            {
                                title: '凭证编码',
                                prop: 'voucherCode',
                            },
                            {
                                title: '登录人',
                                prop: 'userName',
                            },
                            {
                                title: '商品名称',
                                prop: 'goodsName',
                            },
                            {
                                title: '物料名称',
                                prop: 'materialName',
                            },
                            {
                                title: '规格',
                                prop: 'sku',
                            },
                            {
                                title: "物料ID",
                                prop: "materialId",
                            },
                            {
                                title: '入库前库存',
                                prop: 'beforeCount',
                                valueType: 'number'
                            },
                            {
                                title: '入库数量',
                                prop: 'count',
                                valueType: 'number'
                            },
                            {
                                title: '入库单价',
                                prop: 'unitPrice'
                            },
                            // {
                            //     title: '入库单详细总价',
                            //     prop: 'detailTotalPrice'
                            // },
                            {
                                title: '操作时间',
                                prop: 'createTime',
                            },
                        ]
                    },
                ]
                let tb_arr = []
                res.data.forEach((item, index) => {
                    tb_arr.push({
                        index: index+1,
                        code: item.code || '/' ,
                        otherCode:item.otherCode || '/',
                        num:item.num || '/',
                        finishTime:item.finishTime || '/',
                        remark:item.remark || '/',
                        inLibraryTypeName:item.inLibraryTypeName || '/',
                        libraryName:item.libraryName || '/',
                        supplierName:item.supplierName || '/',
                        status: item.status || '/' ,
                        voucherCode: item.voucherCode || '/',
                        userName:item.userName || '/',
                        goodsName: item.goodsName || '/',
                        materialName: item.materialName || '/',
                        sku: item.sku || '/',
                        materialId: item.materialId || '/',
                        beforeCount: item.beforeCount || '0',
                        count: item.count || '/',
                        unitPrice:(item.unitPrice/100).toFixed(2) || '/',
                        // detailTotalPrice: (item.detailTotalPrice/100).toFixed(2) || '/',
                        createTime: item.createTime || '/',
                    })
                })
                exportSheetTable({ fileName: '采购入库单详情', tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false })
                this.setState({
                    selectedKeys: { 1: [] }
                })
            }
        })
    }
    render() {
        let { columns, dataSource, pageData, total, form_show, searchOption, newColumns,sumCount,sumPrice, visible, selectedKeys } = this.state
        const rowSelection = {
            selectedRowKeys: selectedKeys[pageData.pageNo],
            onChange: this.onChange,
        }
        return (
            <div className="p-layout-box commodity-examine">
                {/* <Form layout={'inline'} ref={this.formRef_search} onFinish={() => this.onFinishSearch()} style={{ marginBottom: 12 }}>
                    <Form.Item name={"code"}>
                        <Input style={{ width: 140 }} suffix={<SearchOutlined />} placeholder={"入库单号"} />
                    </Form.Item>
                    <Form.Item>
                        <Space size="small" style={{ marginLeft: 10 }}>
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>
                            <Button onClick={() => this.resetSearch()}>重置</Button>
                        </Space>
                    </Form.Item>
                </Form> */}
                <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
                    onGetValues={(values) => this.onFormSearch(values)}
                    onReset={(values) => this.onReset(values)}
                >
                    <TheButton type="default" size="middle" >总件数：{sumCount}（件）</TheButton>

                    <TheButton type="default" size="middle" style={{marginLeft:"10px"}} >总价格：{sumPrice}（元）</TheButton>
                </TheQueryForm>
                <TheTableExtend
                    columns={columns}
                    onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
                    onTableRefresh={() => this.onTableRefresh()}
                    onColumnsFilter={(value) => this.onColumnsFilter(value)}
                >
                    {/* <TheButton haspermi={['storage:putIn:add']} size="middle" onClick={() => this.props.history.push('/outPutManager/putIn/add/null')} type="primary">新增</TheButton> */}
                    <TheButton size="middle" onClick={() => this.toExport()} type="default">导出</TheButton>
                </TheTableExtend>

                <TheTable
                    scroll={{ x: "max-content", y: '63vh' }}
                    columns={newColumns}
                    dataSource={dataSource}
                    rowKey={record => record.id}
                    rowSelection={rowSelection}
                />
                <ThePagination
                    pageNo={pageData.pageNo}
                    pageSize={pageData.pageSize}
                    total={total}
                    pageChange={this.pageChange}
                />
                <Modal 
                    title={"编辑凭证编号"}
                    visible={visible}
                    footer={null}
                    onCancel={()=>this.handleCancel()}>
                    <Form ref={(ref)=>this.voucherFormRef = ref} onFinish={(values) => this.editVoucher(values)}>
                        <Form.Item label="凭证编码" name={'voucherCode'} >
                            <Input />
                        </Form.Item>
                        <Form.Item>
                            <Button type="default" onClick={() => this.handleCancel()} style={{ 'marginRight': 20 }}>
                                取消
                            </Button>
                            <Button type="primary" htmlType="submit">
                                确定
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        );
    }
}
